﻿using Microsoft.Extensions.Logging;
using NewRetail.Application.Components.Goods.Entity;
using NewRetail.Application.Components.Platform.Entity;
using NewRetail.Application.Core;
using NewRetail.Application.Core.SingleStore;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace NewRetail.Application.Components.Goods
{
    ////商品退货周期 add by cl 20230322
    public interface IGoodsReturnCycleService : IApplicationService
    {
        Task<GoodsCategoryReturnCycle[]> AttachSupplier(GoodsCategoryReturnCycle[] data);
        /// <summary>
        /// 关联商品分类
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        Task<GoodsCategoryReturnCycle[]> AttachGoodsCategory(GoodsCategoryReturnCycle[] data);
    }

    public class GoodsReturnCycleService : ApplicationService, IGoodsReturnCycleService
    {
        private readonly IRepository<GoodsCategoryReturnCycle> goodsReturnCycles;
        private readonly ISingleStoreService singleStoreService;
        private readonly ILogger logger;

        public GoodsReturnCycleService(IRepository<GoodsCategoryReturnCycle> goodsReturnCycles, ISingleStoreService singleStoreService, ILogger<GoodsReturnCycleService> logger)
        {
            this.goodsReturnCycles = goodsReturnCycles;
            this.singleStoreService = singleStoreService;
            this.logger = logger;
        }

        /// <summary>
        /// 关联供应商
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<GoodsCategoryReturnCycle[]> AttachSupplier(GoodsCategoryReturnCycle[] data)
        {
            var db = await this.goodsReturnCycles.GetDbContextAsync();

            await db.AttachData<Supplier, GoodsCategoryReturnCycle>(data, x => x.supplierId, (m, arr) =>
            {
                m.Supplier = arr.FirstOrDefault();
            });

            return data;
        }

        /// <summary>
        /// 关联商品分类
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<GoodsCategoryReturnCycle[]> AttachGoodsCategory(GoodsCategoryReturnCycle[] data)
        {
            var db = await this.goodsReturnCycles.GetDbContextAsync();

            await db.AttachData<GoodsCategory, GoodsCategoryReturnCycle>(data,
                idGetter: x => x.categoryId,
                action: (m, arr) => m.GoodsCategory = arr.FirstOrDefault());

            return data;
        }
    }
}
